package com.fl.nj.controller;

import com.fl.nj.entity.Device;
import com.fl.nj.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 设备Controller
 * 提供RESTful API接口，供Vue前端调用
 */
@RestController
@RequestMapping("/api/devices")
public class DeviceController {
    @Autowired
    private DeviceService deviceService;

    /**
     * 获取所有设备列表，支持设备名称模糊搜索
     * @param deviceName 设备名称关键词（可选）
     * @param areaId 区域ID（可选）
     * @return 设备列表
     */
    @GetMapping
    public ResponseEntity<List<Device>> getAll(@RequestParam(value = "deviceName", required = false) String deviceName, 
                                             @RequestParam(value = "areaId", required = false) Long areaId) {
        List<Device> deviceList;
        if (deviceName != null && !deviceName.isEmpty()) {
            deviceList = deviceService.searchByDeviceName(deviceName);
        } else if (areaId != null) {
            deviceList = deviceService.getByAreaId(areaId);
        } else {
            deviceList = deviceService.getAll();
        }
        return ResponseEntity.ok(deviceList);
    }

    /**
     * 根据ID获取设备
     * @param id 设备ID
     * @return 设备对象
     */
    @GetMapping("/{id}")
    public ResponseEntity<Device> getById(@PathVariable Long id) {
        Device device = deviceService.getById(id);
        if (device == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(device);
    }

    /**
     * 根据设备名称获取设备
     * @param deviceName 设备名称
     * @return 设备对象
     */
    @GetMapping("/name/{deviceName}")
    public ResponseEntity<Device> getByDeviceName(@PathVariable String deviceName) {
        Device device = deviceService.getByDeviceName(deviceName);
        if (device == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(device);
    }

    /**
     * 根据区域ID获取设备列表
     * @param areaId 区域ID
     * @return 设备列表
     */
    @GetMapping("/area/{areaId}")
    public ResponseEntity<List<Device>> getByAreaId(@PathVariable Long areaId) {
        List<Device> deviceList = deviceService.getByAreaId(areaId);
        return ResponseEntity.ok(deviceList);
    }

    /**
     * 添加设备
     * @param device 设备对象
     * @return 添加结果
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> save(@RequestBody Device device) {
        Map<String, Object> result = new HashMap<>();
        try {
            deviceService.save(device);
            result.put("success", true);
            result.put("message", "添加成功");
            result.put("data", device);
            return ResponseEntity.status(HttpStatus.CREATED).body(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 更新设备
     * @param id 设备ID
     * @param device 设备对象
     * @return 更新结果
     */
    @PutMapping("/{id}")
    public ResponseEntity<Map<String, Object>> update(@PathVariable Long id, @RequestBody Device device) {
        device.setId(id);
        Map<String, Object> result = new HashMap<>();
        try {
            deviceService.update(device);
            result.put("success", true);
            result.put("message", "更新成功");
            result.put("data", device);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 删除设备
     * @param id 设备ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> delete(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            deviceService.delete(id);
            result.put("success", true);
            result.put("message", "删除成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 获取设备的数据库数量
     * @param id 设备ID
     * @return 数据库数量
     */
    @GetMapping("/{id}/database-count")
    public ResponseEntity<Map<String, Integer>> countDatabases(@PathVariable Long id) {
        int count = deviceService.countDatabases(id);
        Map<String, Integer> result = new HashMap<>();
        result.put("count", count);
        return ResponseEntity.ok(result);
    }
}